/*
 * @author: wizardc
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

namespace DouEditor.Asset
{
    /// <summary>
    /// 对特定定制的文件改变进行监听
    /// </summary>
    public class AssetMonitor : AssetPostprocessor
    {
        private static List<IAssetMonitor> _assetMonitors = new List<IAssetMonitor>();

        static AssetMonitor()
        {
            // _assetMonitors.Add(new XXXMonitor());
        }

        void OnPreprocessAsset()
        {
            foreach (IAssetMonitor assetMonitor in _assetMonitors)
            {
                bool needProcess = false;
                if (!string.IsNullOrWhiteSpace(assetMonitor.filePattern))
                {
                    if (Regex.IsMatch(assetPath, assetMonitor.filePattern))
                    {
                        needProcess = true;
                    }
                }
                else if (assetMonitor.fileExtension != null)
                {
                    string ext = Path.GetExtension(assetPath);
                    foreach (string e in assetMonitor.fileExtension)
                    {
                        if (ext.Equals(e))
                        {
                            needProcess = true;
                            break;
                        }
                    }
                }

                if (needProcess)
                {
                    try
                    {
                        assetMonitor.Process(assetPath);
                    }
                    catch (Exception e)
                    {
                        Debug.LogError("文件处理错误：" + e);
                    }
                }
            }
        }
    }
}
